package it.avantsoft.ls.gl.message;

import it.avantsoft.ls.gl.data.AddressBook;

import java.io.DataOutputStream;
import java.io.IOException;

public class ABMessage extends GroupLeaderMessage {
    private String groupLeaderId;
    private String childId;
    private AddressBook ab;
    private AddressBook ab2;

    public ABMessage(DataOutputStream out, String groupLeaderId, String childId, AddressBook ab) {
        super(out);
        this.groupLeaderId = groupLeaderId;
        this.childId = childId;
        this.ab = ab;
    }

    public ABMessage(DataOutputStream out, String groupLeaderId, String childId, AddressBook ab, AddressBook ab2) {
        this(out, groupLeaderId, childId, ab);
        this.ab2 = ab2;
    }

    public boolean send() {
        boolean sent = false;
        byte[] abToByte = ab.toByte();
        byte[] ab2ToByte = null;
        byte abNumber = 1;
        if (ab2 != null) {
            if (ab2.getAbID() == AddressBook.CENTERAB_ID)
                ab2ToByte = ab2.toByte();
            abNumber = 2;
        }
        try {
            writeByte(ADDRESS_BOOK);
            if (groupLeaderId != null) {
                writeUTF(groupLeaderId);
            } else {
                writeUTF("");
            }
            writeUTF(childId);
            writeByte(abNumber);
            writeInt(ab.getAbID());
            writeInt(abToByte.length);
            write(abToByte);
            if (ab2 != null) {
                writeInt(ab2.getAbID());
                writeInt(ab2ToByte.length);
                write(ab2ToByte);
            }

            flush();
            sent = true;
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return sent;
    }

    public String toString() {
        return "ABMessage{" +
                "childId='" + childId + '\'' +
                ", groupLeaderId='" + groupLeaderId + '\'' +
                ", ab=" + ab +
                ", ab2=" + ab2 +
                '}';
    }
}
